package cn.iocoder.mall.shop.application.controller;

import cn.hutool.core.date.DateTime;
import cn.iocoder.common.utils.common.annotation.AutoLog;
import cn.iocoder.common.utils.common.api.vo.Result;
import cn.iocoder.common.utils.common.system.query.QueryGenerator;
import cn.iocoder.common.utils.common.system.util.JwtUtil;
import cn.iocoder.common.utils.common.system.vo.UserInfo;
import cn.iocoder.common.utils.common.util.ObjectUtils;
import cn.iocoder.common.utils.common.util.UUIDGenerator;
import cn.iocoder.common.utils.common.util.json.JacksonUtils;
import cn.iocoder.common.utils.common.util.oConvertUtils;
import cn.iocoder.mall.shop.application.vo.ShopVO;
import cn.iocoder.mall.shop.service.entities.Shop;
import cn.iocoder.mall.shop.service.entities.ShopClerkRelationShip;
import cn.iocoder.mall.shop.service.entities.ShopDTO;
import cn.iocoder.mall.shop.service.entities.ShopSellerRe;
import cn.iocoder.mall.shop.service.service.IShopClerkRelationShipService;
import cn.iocoder.mall.shop.service.service.IShopService;
import cn.iocoder.mall.shop.service.utils.DistanceUtil;
import cn.iocoder.mall.shop.service.utils.GeoHash;
import cn.iocoder.mall.shop.service.utils.RedisUtil;
import cn.iocoder.mall.shop.service.vo.ShopTpyeVO;
import cn.iocoder.mall.shop.service.vo.StatusVo;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jdk.nashorn.internal.ir.annotations.Reference;
import lombok.extern.slf4j.Slf4j;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 商铺
 * @Author: jeecg-boot
 * @Date: 2019-10-23
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "商铺")
@RestController
@RequestMapping("/shop")
public class ShopController {
    @Autowired
    private IShopService shopService;


    @Autowired
    private IShopClerkRelationShipService shopClerkRelationShipService;

    @Autowired
    private RedisUtil redisUtil;


    /**
     * 分页列表查询
     *
     * @param shop
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "商铺-分页列表查询")
    @ApiOperation(value = "商铺-分页列表查询", notes = "商铺-分页列表查询")
    @GetMapping(value = "/app/shopList")
    public Result<IPage<Shop>> queryPageList(Shop shop,
                                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                             HttpServletRequest req) {
        Result<IPage<Shop>> result = new Result<IPage<Shop>>();
        shop.setCoordinate(null);
        QueryWrapper<Shop> queryWrapper = QueryGenerator.initQueryWrapper(shop, req.getParameterMap());
        Page<Shop> page = new Page<Shop>(pageNo, pageSize);
        //增加判断条件，只查询未删除的
        queryWrapper.eq("is_delete",0);
        queryWrapper.eq("shop_status",1);

        queryWrapper.select(Shop.class, info -> !info.getColumn().equals("update_time")
                && !info.getColumn().equals("create_time"));
        IPage<Shop> pageList = shopService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    @AutoLog(value = "商铺-分页列表查询")
    @ApiOperation(value = "商铺-根据坐标获取附近的人", notes = "商铺-分页列表查询")
    @GetMapping(value = "/app/shopListOfRange")
    public Result<?> shopListOfRange(@RequestParam String coordinate ,@RequestParam(name = "level",defaultValue = "1",required = false) Integer level,
                                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                             HttpServletRequest req) {

        String co=GeoHash.encode(coordinate);
        if (co==null){
            return Result.error("坐标信息错误");
        }
        final String geoCoordinate=co.substring(0,8-level);
        Page page=new Page(pageNo,pageSize);
        IPage<Shop> shopIPage=shopService.getListByCoordinate(page,geoCoordinate);
        shopIPage.setRecords(shopIPage.getRecords().stream().
                sorted(Comparator.comparingDouble(o->DistanceUtil.distance(geoCoordinate,o.getCoordinate())))
                .collect(Collectors.toList()));
        return Result.ok(shopIPage);
    }
    /**
     * 分页列表查询--web
     *
     * @param shopTpyeVO
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "商铺-分页列表查询")
    @ApiOperation(value = "商铺-分页列表查询", notes = "商铺-分页列表查询")
    @GetMapping(value = "/web/shopList")
    public Result<IPage<Shop>> queryWebPageList(ShopTpyeVO shopTpyeVO,
                                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                HttpServletRequest req) {
        Result<IPage<Shop>> result = new Result<IPage<Shop>>();
        Shop shop=new Shop();
        BeanUtils.copyProperties(shopTpyeVO,shop);
        QueryWrapper<Shop> queryWrapper = QueryGenerator.initQueryWrapper(shop, req.getParameterMap());
        Page<Shop> page = new Page<Shop>(pageNo, pageSize);
        //增加判断条件，只查询未删除的
        queryWrapper.eq("is_delete",0);
        queryWrapper.select(Shop.class, info -> !info.getColumn().equals("update_time")
                && !info.getColumn().equals("create_time"));
        IPage<Shop> pageList = shopService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }


    @GetMapping("/merchant/list")
    public Result<?>  getAllShopListOfSeller( @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize){


        UserInfo userInfo=JwtUtil.getUserInfoByToken();
        log.info("");
        if (0==userInfo.getType()){
            return Result.ok(shopService.getAllShopListOfSeller(new Page().setTotal(pageNo).setSize(pageSize), JwtUtil.getUserIdByToken()));

        }else {
            return Result.ok(shopService.getShopPageListOfClerk(new Page().setTotal(pageNo).setSize(pageSize), JwtUtil.getUserIdByToken()));

        }


    }

    /**
     * 管理员添加商铺
     *
     * @param shopvo
     * @return
     */
    @AutoLog(value = "商铺-添加")
    @ApiOperation(value = "商铺-添加", notes = "商铺-添加")
    @PostMapping(value = "/web/add")
    public Result<Shop> add(@RequestBody ShopVO shopvo) {
        Result<Shop> result = new Result<Shop>();
        Shop shop=new Shop();
        BeanUtils.copyProperties(shopvo,shop);
        try {
            String shopId=UUIDGenerator.generate();
            shop.setId(shopId);
            shop.setCoordinate(GeoHash.encode(shop.getCoordinate()));
            shopService.save(shop);
            //往商户商铺关联表中添加记录
            shopService.saveRelationshipTable(shopId,shopvo.getSellerId());
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败:"+e.getMessage());
        }
        return result;
    }

    /**
     * 商户添加商铺
     *
     * @param shop
     * @return
     */
    @AutoLog(value = "商铺-添加")
    @ApiOperation(value = "商铺-添加", notes = "商铺-添加")
    @PostMapping(value = "/merchant/add")
    public Result<?> add(@RequestBody Shop shop) {
        Result<Shop> result = new Result<Shop>();
            String sellerId = JwtUtil.getUserInfoByToken().getUserId();
            QueryWrapper<Shop> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("shop_name",shop.getShopName());
            Shop dbData=shopService.getOne(queryWrapper);
            if (dbData!=null) {
                return result.error500("商铺名称已存在");
            }
            shop.setId(UUIDGenerator.generate());

            //获取商铺id
            shop.setCreateTime(new Date());
            try {
                String[] coordinat=shop.getCoordinate().split(",");
                shop.setCoordinate(GeoHash.encode(Double.parseDouble(coordinat[0]),Double.parseDouble(coordinat[1])));

            }catch (Exception e){
                return Result.error("商店坐标有误");
            }
        try {
            shopService.save(shop);
            //往商户商铺关联表中添加记录
            shopService.saveRelationshipTable(shop.getId(),sellerId);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    @PostMapping("/merchant/updateShopStatus")
    public Result<?> updateShopStatus(@RequestBody StatusVo vo){
        shopService.updateStatus(vo.getShopId(),vo.getStatus());
        return Result.ok();

    }
    /**
     * 编辑--web
     *
     * @param shop
     * @return
     */
    @AutoLog(value = "商铺-编辑")
    @ApiOperation(value = "商铺-编辑", notes = "商铺-编辑")
    @PostMapping(value = "/web/edit")
    public Result<Shop> edit(@RequestBody Shop shop) {
        Result<Shop> result = new Result<Shop>();
        Shop shopEntity = shopService.getById(shop.getId());
        if (shopEntity == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = shopService.updateById(shop);
            //TODO 返回false说明什么？
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

    /**
     * 通过id删除 逻辑删除商铺
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "商铺-通过id删除", notes = "商铺-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        try {
            shopService.removeShopById(id);
        } catch (Exception e) {
            log.error("删除失败", e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "商铺-批量删除")
    @ApiOperation(value = "商铺-批量删除", notes = "商铺-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<Shop> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<Shop> result = new Result<Shop>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.shopService.removeShopByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "商铺-通过id查询")
    @ApiOperation(value = "商铺-通过id查询", notes = "商铺-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<Shop> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<Shop> result = new Result<Shop>();
        Shop shop = shopService.getById(id);
        if (shop == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(shop);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
        // Step.1 组装查询条件
        QueryWrapper<Shop> queryWrapper = null;
        try {
            String paramsStr = request.getParameter("paramsStr");
            if (oConvertUtils.isNotEmpty(paramsStr)) {
                String deString = URLDecoder.decode(paramsStr, "UTF-8");
                Shop shop = JSON.parseObject(deString, Shop.class);
                queryWrapper = QueryGenerator.initQueryWrapper(shop, request.getParameterMap());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<Shop> pageList = shopService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "商铺列表");
        mv.addObject(NormalExcelConstants.CLASS, Shop.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("商铺列表数据", "导出人:Jeecg", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<Shop> listShops = ExcelImportUtil.importExcel(file.getInputStream(), Shop.class, params);
                shopService.saveBatch(listShops);
                return Result.ok("文件导入成功！数据行数:" + listShops.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }



    /**
     * 店铺分配店员
     * @param shopClerkRelationShip
     * @return
     */
    @PostMapping("/merchant/storeDistributionClerk")
    public Result StoreDistributionClerk(@Valid @RequestBody ShopClerkRelationShip shopClerkRelationShip, BindingResult bindingResult){
        ShopClerkRelationShip shopClerk;
        if(bindingResult.hasErrors()){
            return Result.error(JacksonUtils.toJSONString(bindingResult.getAllErrors()));
        }
        String[] ids = shopClerkRelationShip.getClerkId().split(",");
        for (int i = 0; i<ids.length;i++){
            shopClerk = new ShopClerkRelationShip();
            shopClerk.setShopId(shopClerkRelationShip.getShopId());
            shopClerk.setClerkId(ids[i]);
            shopClerkRelationShipService.save(shopClerk);
        }
        return Result.ok("分配成功");
    }

    /**
     * 店铺解绑店员
     * @param shopClerkRelationShip
     * @return
     */
    @PostMapping("/merchant/deleteShopAssistants")
    public Result deleteShopAssistants(@RequestBody ShopClerkRelationShip shopClerkRelationShip){
        String[] ids = shopClerkRelationShip.getClerkId().split(",");
        int count = shopClerkRelationShipService.removeByShopIdsAndClerkIds(shopClerkRelationShip.getShopId(), Arrays.asList(ids));
        if (count > 0){
            return Result.ok("解绑成功");
        }else {
            return Result.error("解绑失败");
        }
    }

    /**
     * 查看店铺详情
     * @param shopId
     * @return
     */
    @GetMapping("/merchant/shopDetail")
    public Result<?> shopDetail(@RequestParam(name = "shopId", required = true) String shopId){

        Result<Shop> result = new Result<Shop>();

        Shop shopEntity = shopService.getById(shopId);

        return Result.ok(shopEntity);
    }


    @PostMapping("/merchant/updateShopInfo")
    public Result<?> updateShopInfo(@RequestBody Shop shop){
        if (shop.getId()==null){
            return Result.error("参数错误,id为空");
        }
        ShopSellerRe shopSellerRe=shopService.getShopSellerShipByShopId(shop.getId());
        if (!ObjectUtils.StringsIsEquals(JwtUtil.getUserIdByToken(), shopSellerRe.getSellerId())){
            return Result.error("不是该商户的店铺");
        }
        try {
            //TODO  是否需要修改为待审核
            shop.setMobile(null);
            shop.setUpdateTime(new DateTime());
            shopService.updateById(shop);
            return  Result.ok("更新成功");
        }catch (Exception e){
            return Result.error("更新失败");
        }


    }

    /**
     * @param params
     * @return
     */
    @PostMapping("/merchant/delete")
    public Result<?> sellerDeleteShopById(@RequestBody Map<String ,Object> params){
        if (params.get("shopId")==null){
            return Result.error("缺少商铺id");
        }
        String shopId= (String) params.get("shopId");
        String code=(String) params.get("code");
        ShopSellerRe shopSellerRe=shopService.getShopSellerShipByShopId(shopId);
        if (!shopSellerRe.getSellerId().equals(JwtUtil.getUserIdByToken())){
            return Result.error("该商铺不属于该商户");
        }
        Shop temp=new Shop();
        temp.setId(shopId);
        temp.setIsDelete(1);
        try {
            Shop shop=shopService.getById(shopId);
            if (shop!=null){
            }
        String c=(String)redisUtil.getSellerCode(shop.getMobile());
            if (code==null||!code.equals(c)){
                return Result.error("验证码错误");
            }

            shopService.updateById(temp);
            shopService.deleteSellerShopRelationByShopId(shopId);
        }catch (Exception e){
            log.error(e.getMessage());
            return Result.error("删除失败");
        }

        return Result.ok("删除成功");

    }
    @DeleteMapping("/web/delete")
    public Result<?> webDeleteShopById(@RequestParam(name="id",required=true) String id){
        if (id==null){
            return Result.error("缺少商铺id");
        }
        Shop temp=new Shop();
        temp.setId(id);
        temp.setIsDelete(1);
        try {
            shopService.updateById(temp);
            shopService.deleteSellerShopRelationByShopId(id);
        }catch (Exception e){
            log.error(e.getMessage());
            return Result.error("删除失败");
        }

        return Result.ok("删除成功");

    }

    /**
     * 批量删除店铺--web
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/web/deleteWebBatch")
    public Result<Shop> deleteWebBatch(@RequestParam(name="ids",required=true) String ids) {
        Result<Shop> result = new Result<Shop>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.shopService.removeShopByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    @PostMapping("/web/reviewShopInfo")
    public Result reviewShopInfo(@RequestBody ShopDTO shopDTO){
        if (shopDTO.getId()==null||shopDTO.getShopStatus()==null){
            return Result.error("参数不足");
        }
        else {
            shopService.updateShopStatus(shopDTO.getId(),shopDTO.getShopStatus());
        }
        return Result.ok("操作成功");
    }


}
